package com.darker.yygh.sms.controller;

import com.darker.yygh.result.Result;
import com.darker.yygh.result.ResultCodeEnum;
import com.darker.yygh.sms.service.SmsService;
import com.darker.yygh.sms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class SmsApiController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    //发送手机验证码
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis获取验证码，如果获得得到则 不再发送
        String code = redisTemplate.opsForValue().get(phone);
        //已经发送过验证码直接返回
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果从redis获取不到验证码 则发送验证码
        code= RandomUtil.getFourBitRandom(); //生成验证码
        boolean isSend=smsService.send(phone,code);
        //发送验证码成功后把验证码存入redis缓存
        if (isSend){
            //验证码两分钟后失效
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        }
        else {
            return Result.fail().message("发送验证码失败");
        }


    }
}
